<?php
namespace Model;

class PostHandler {

	private $database = NULL;
	const POST_EMPTY = 0;
	const POST_SUCCESS = 1;
	const POST_FAILED = 2;
	const POST_SAVED = 3;

	public function __construct($a_database) {
		$this -> database = $a_database;
	}

	//Visar alla inläggen
	public function getAllposts() {

		$sql = "SELECT * FROM post ORDER BY p_id desc";
		$stmt = $this -> database -> SqlStatement($sql);
		$stmt -> execute();
		if ($stmt -> bind_result($postID, $title, $content, $date) == FALSE) {
			throw new \Exception($this -> m_mysqli -> error);
		}

		//lägger dom i en array
		$ret = new PostArray();
		while ($stmt -> fetch()) {
			$post = new Post($postID, $title, $content, $date);
			$ret -> add($post);
		}

		$stmt -> close();

		return $ret;
	}

	//Hämtar vald inlägg
	public function getPostByID($postID) {
		$sql = "select * from post where p_id = ?";
		$stmt = $this -> database -> SqlStatement($sql);
		$stmt -> bind_param("i", $postID);

		$stmt -> execute();
		if ($stmt -> bind_result($postID, $title, $content, $date) == FALSE) {
			throw new \Exception($this -> m_mysqli -> error);
		}
		if ($stmt -> fetch()) {
			$ret = new Post($postID, $title, $content, $date);
		} else {
			throw new \Exception("hittar inte inlägget med id=" . $postID);
		}
		$stmt -> close();
		return $ret;
	}

	//Skapar nytt inlägg
	public function newPost($title, $content) {
		$validate = new \Common\Validator();
		if (isset($title) && isset($content)) {
			$title1 = $validate -> filterHTML($title);
			$content1 = $validate -> filterJavascript($content);
			$sql = "INSERT INTO post (title, content) VALUES (?, ?)";

			if ($title == '' || $content == '') {
				return self::POST_EMPTY;
			}

			if ($stmt = $this -> database -> SqlStatement($sql)) {
				$stmt -> bind_param('ss', $title1, $content1);

				$stmt -> execute();

				$stmt -> close();

				return self::POST_SUCCESS;
			}
		}
		return self::POST_FAILED;
	}

	//Redigera inlägg
	public function EditPost($p_id, $title, $content) {

		if (isset($title) && isset($content)) {
			$sql = "UPDATE post SET title = ?, content = ? WHERE p_id = ? ";

			if ($title == '' || $content == '') {
				return self::POST_EMPTY;
			}
			if ($stmt = $this -> database -> SqlStatement($sql)) {
				$stmt -> bind_param('ssi', $title, $content, $p_id);

				$stmt -> execute();

				$stmt -> close();

				return self::POST_SAVED;
			}
		}
		return self::POST_FAILED;
	}

	//Radera inlägg
	public function DeletePost($p_id) {

		if (isset($p_id)) {
			$sql = "DELETE FROM post WHERE p_id = ?";

			if ($stmt = $this -> database -> SqlStatement($sql)) {

				$stmt -> bind_param('i', $p_id);

				$stmt -> execute();

				$stmt -> close();
				return true;
			}
		}

		return false;
	}

}
